import logging
import subprocess
from pathlib import Path
import config
import json
import time
from jinja2 import Template
import traceback
import os
import urllib.parse

logger = logging.getLogger()

# 定义多个CDN源作为备选方案
CDN_SOURCES = [
    {
        "chart_js": "https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js",
        "moment_js": "https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js",
        "adapter_js": "https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0/dist/chartjs-adapter-moment.min.js"
    },
    {
        "chart_js": "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js",
        "moment_js": "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js",
        "adapter_js": "https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.0/chartjs-adapter-moment.min.js"
    },
    {
        "chart_js": "https://unpkg.com/chart.js@3.7.0/dist/chart.min.js",
        "moment_js": "https://unpkg.com/moment@2.29.1/min/moment.min.js",
        "adapter_js": "https://unpkg.com/chartjs-adapter-moment@1.0.0/dist/chartjs-adapter-moment.min.js"
    }
]


def generate_performance_report(case_name, performance_data, device_info=None, is_retry=False):
    """生成性能报告HTML文件 - 包含超标标记和摘要"""
    try:
        # 确保性能报告目录存在
        perf_report_dir = config.PERFORMANCE_REPORT_DIR
        perf_report_dir.mkdir(parents=True, exist_ok=True)

        # 在文件名中添加重试标识
        retry_suffix = "_retry" if is_retry else ""
        timestamp = time.strftime("%Y%m%d%H%M%S")
        perf_report_file = perf_report_dir / f"perf_report_{case_name}{retry_suffix}_{timestamp}.html"

        # 检查是否有性能数据
        if not performance_data:
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <title>{case_name} - 性能报告</title>
                <style>
                    body {{ font-family: Arial, sans-serif; padding: 20px; }}
                    .no-data {{ text-align: center; margin-top: 50px; font-size: 18px; color: #666; }}
                </style>
            </head>
            <body>
                <h1>{case_name} - 性能报告</h1>
                <div class="no-data">
                    <p>性能监控未启用或未收集到数据</p>
                    <p>请检查配置或确保应用正常运行</p>
                </div>
            </body>
            </html>
            """
            with open(perf_report_file, "w", encoding="utf-8") as f:
                f.write(html_content)
            logger.info(f"生成了空性能报告: {perf_report_file}")
            return perf_report_file.as_uri()

        # 准备图表数据
        timestamps = [d["timestamp"] for d in performance_data]

        # 内存数据 - 正确处理字典结构
        rss_data = []
        virt_data = []

        for d in performance_data:
            # 安全获取内存数据
            memory_dict = d.get("memory")
            if memory_dict and isinstance(memory_dict, dict):
                rss_data.append(memory_dict.get("rss"))
                virt_data.append(memory_dict.get("virt"))
            else:
                rss_data.append(None)
                virt_data.append(None)

        # 其他数据
        cpu_data = [d.get("cpu") for d in performance_data]
        battery_data = [d.get("battery") for d in performance_data]
        temperature_data = [d.get("temperature") for d in performance_data]
        fps_data = [d.get("fps") for d in performance_data]

        # 计算平均值 - 仅使用有效数据
        valid_rss = [m for m in rss_data if m is not None]
        valid_virt = [m for m in virt_data if m is not None]
        valid_cpu = [c for c in cpu_data if c is not None]
        valid_fps = [f for f in fps_data if f is not None]
        valid_temperature = [t for t in temperature_data if t is not None]
        valid_battery = [b for b in battery_data if b is not None]

        avg_rss = round(sum(valid_rss) / len(valid_rss)) if valid_rss and len(valid_rss) > 0 else 0
        avg_virt = round(sum(valid_virt) / len(valid_virt)) if valid_virt and len(valid_virt) > 0 else 0
        avg_cpu = round(sum(valid_cpu) / len(valid_cpu), 1) if valid_cpu and len(valid_cpu) > 0 else 0
        avg_fps = round(sum(valid_fps) / len(valid_fps), 1) if valid_fps and len(valid_fps) > 0 else 0
        avg_temperature = round(sum(valid_temperature) / len(valid_temperature), 1) if valid_temperature and len(
            valid_temperature) > 0 else 0

        # 计算耗电量
        battery_consumption = 0
        if valid_battery and len(valid_battery) > 1:
            start_battery = valid_battery[0]
            end_battery = valid_battery[-1]
            if start_battery is not None and end_battery is not None:
                battery_consumption = round(start_battery - end_battery, 1)

        # 创建HTML报告
        report_time = time.strftime("%Y-%m-%d %H:%M:%S")

        # 准备JSON格式的数据
        chart_data = {
            "timestamps": timestamps,
            "rss_data": rss_data,
            "virt_data": virt_data,
            "cpu_data": cpu_data,
            "temperature_data": temperature_data,
            "fps_data": fps_data
        }
        chart_data_json = json.dumps(chart_data)

        # 使用CDN源
        cdn_source = CDN_SOURCES[0]

        # 计算超标情况
        exceeded_summary = {
            "rss_peak": 0,
            "virt_peak": 0,
            "cpu_peak": 0,
            "fps_min": 0,
            "temp_peak": 0
        }

        for data in performance_data:
            if "exceeded_thresholds" in data:
                for key in data["exceeded_thresholds"]:
                    if key in exceeded_summary:
                        exceeded_summary[key] += 1

        # 使用Jinja2模板生成报告 - 使用完整的模板字符串
        template_str = '''
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>{{ case_name }} - 性能报告</title>
            <!-- 使用CDN资源 -->
            <script src="{{ chart_js_url }}"></script>
            <script src="{{ moment_js_url }}"></script>
            <script src="{{ adapter_js_url }}"></script>
            <style>
                :root {
                    --primary-color: #3498db;
                    --success-color: #2ecc71;
                    --warning-color: #f39c12;
                    --danger-color: #e74c3c;
                    --light-bg: #f8f9fa;
                    --card-bg: #ffffff;
                    --text-color: #333333;
                    --border-color: #e0e0e0;
                    --grid-color: #f0f0f0;
                }

                body { 
                    font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif; 
                    margin: 0; 
                    padding: 20px; 
                    background-color: var(--light-bg);
                    color: var(--text-color);
                    line-height: 1.6;
                }

                .container { 
                    max-width: 1200px; 
                    margin: 0 auto; 
                }

                .header { 
                    background: linear-gradient(135deg, var(--primary-color), #2c3e50); 
                    color: white; 
                    padding: 25px; 
                    border-radius: 12px; 
                    margin-bottom: 25px; 
                    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
                    text-align: center;
                }

                .stats-grid { 
                    display: grid; 
                    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); 
                    gap: 20px; 
                    margin-bottom: 30px; 
                }

                .stat-card { 
                    background: var(--card-bg); 
                    border-radius: 10px; 
                    padding: 20px; 
                    box-shadow: 0 4px 8px rgba(0,0,0,0.05); 
                    text-align: center;
                    transition: transform 0.3s ease;
                }

                .stat-card:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 8px 16px rgba(0,0,0,0.1);
                }

                .stat-value { 
                    font-size: 28px; 
                    font-weight: bold; 
                    margin: 15px 0;
                    color: var(--primary-color);
                }

                .chart-container { 
                    background: var(--card-bg); 
                    border-radius: 10px; 
                    padding: 25px; 
                    margin-bottom: 30px; 
                    box-shadow: 0 4px 8px rgba(0,0,0,0.05);
                }

                .chart-title { 
                    font-size: 20px; 
                    margin-bottom: 20px; 
                    color: var(--text-color); 
                    border-bottom: 2px solid var(--border-color); 
                    padding-bottom: 15px;
                    font-weight: 600;
                }

                .chart-wrapper {
                    position: relative;
                    height: 350px;
                    width: 100%;
                }

                .device-info { 
                    background: var(--card-bg); 
                    border-radius: 10px; 
                    padding: 25px; 
                    margin-bottom: 30px; 
                    box-shadow: 0 4px 8px rgba(0,0,0,0.05);
                }

                .info-grid { 
                    display: grid; 
                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
                    gap: 15px; 
                }

                .info-item { 
                    margin-bottom: 10px; 
                }

                .info-label { 
                    font-weight: bold; 
                    color: #7f8c8d; 
                }

                .table-container { 
                    overflow-x: auto; 
                }

                table { 
                    width: 100%; 
                    border-collapse: collapse; 
                }

                th, td { 
                    padding: 12px 15px; 
                    text-align: left; 
                    border-bottom: 1px solid var(--border-color); 
                }

                th { 
                    background-color: var(--light-bg); 
                    font-weight: 600; 
                    position: sticky;
                    top: 0;
                }

                tr:hover { 
                    background-color: var(--grid-color); 
                }

                .footer { 
                    text-align: center; 
                    margin-top: 30px; 
                    color: #7f8c8d; 
                    font-size: 14px; 
                }

                .no-data {
                    text-align: center;
                    padding: 20px;
                    color: #999;
                    font-style: italic;
                }

                /* 超标标记样式 */
                .exceeded-threshold {
                    background-color: #ffcccc !important; /* 浅红色背景 */
                    font-weight: bold;
                    position: relative;
                }
                .exceeded-threshold::after {
                    content: "⚠";
                    position: absolute;
                    right: 5px;
                    color: #d9534f;
                }
                .exceeded-row {
                    background-color: #fff3f3 !important; /* 行高亮 */
                }

                .exceeded-summary {
                    background-color: #fff8e6;
                    border-left: 4px solid #ffc107;
                    padding: 15px;
                    margin: 20px 0;
                    border-radius: 0 4px 4px 0;
                }
                .exceeded-summary h3 {
                    margin-top: 0;
                    color: #d9534f;
                }
                .exceeded-summary ul {
                    margin-bottom: 0;
                    padding-left: 20px;
                }
                .exceeded-summary li {
                    margin-bottom: 5px;
                }
                .exceeded-summary .warning {
                    color: #d9534f;
                    font-weight: bold;
                }

                /* 响应式设计 */
                @media (max-width: 768px) {
                    .stats-grid {
                        grid-template-columns: 1fr;
                    }

                    .chart-wrapper {
                        height: 250px;
                    }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>{{ case_name }} - 性能报告</h1>
                    <p>生成时间: {{ report_time }}</p>
                </div>

                {% if device_info %}
                <div class="device-info">
                    <h2>设备信息</h2>
                    <div class="info-grid">
                        <div class="info-item">
                            <div class="info-label">设备型号</div>
                            <div>{{ device_info.model }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">系统版本</div>
                            <div>{{ device_info.version }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">分辨率</div>
                            <div>{{ device_info.resolution }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">CPU</div>
                            <div>{{ device_info.cpu }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-label">内存</div>
                            <div>{{ device_info.memory }}</div>
                        </div>
                    </div>
                </div>
                {% endif %}

                <div class="stats-grid">
                    <div class="stat-card">
                        <div>平均物理内存</div>
                        <div class="stat-value">{{ avg_rss }} KB</div>
                    </div>
                    <div class="stat-card">
                        <div>平均虚拟内存</div>
                        <div class="stat-value">{{ avg_virt }} KB</div>
                    </div>
                    <div class="stat-card">
                        <div>平均CPU</div>
                        <div class="stat-value">{{ avg_cpu }} %</div>
                    </div>
                    <div class="stat-card">
                        <div>平均FPS</div>
                        <div class="stat-value">{{ avg_fps }}</div>
                    </div>
                    <div class="stat-card">
                        <div>平均温度</div>
                        <div class="stat-value">{{ avg_temperature }} °C</div>
                    </div>
                    <div class="stat-card">
                        <div>耗电量</div>
                        <div class="stat-value">{{ battery_consumption }} %</div>
                    </div>
                </div>

                <!-- 超标摘要 -->
                <div class="exceeded-summary">
                    <h3>阈值超标情况统计</h3>
                    <ul>
                        <li>物理内存超标次数: <span class="warning">{{ exceeded_summary.rss_peak }}</span></li>
                        <li>虚拟内存超标次数: <span class="warning">{{ exceeded_summary.virt_peak }}</span></li>
                        <li>CPU超标次数: <span class="warning">{{ exceeded_summary.cpu_peak }}</span></li>
                        <li>FPS不足次数: <span class="warning">{{ exceeded_summary.fps_min }}</span></li>
                        <li>温度超标次数: <span class="warning">{{ exceeded_summary.temp_peak }}</span></li>
                    </ul>
                </div>

                <div class="chart-container">
                    <div class="chart-title">物理内存使用趋势 (KB)</div>
                    <div class="chart-wrapper">
                        <canvas id="rssChart"></canvas>
                    </div>
                </div>

                <div class="chart-container">
                    <div class="chart-title">虚拟内存使用趋势 (KB)</div>
                    <div class="chart-wrapper">
                        <canvas id="virtChart"></canvas>
                    </div>
                </div>

                <div class="chart-container">
                    <div class="chart-title">CPU使用率趋势 (%)</div>
                    <div class="chart-wrapper">
                        <canvas id="cpuChart"></canvas>
                    </div>
                </div>

                <div class="chart-container">
                    <div class="chart-title">温度趋势 (°C)</div>
                    <div class="chart-wrapper">
                        <canvas id="tempChart"></canvas>
                    </div>
                </div>

                <div class="chart-container">
                    <div class="chart-title">FPS趋势</div>
                    <div class="chart-wrapper">
                        <canvas id="fpsChart"></canvas>
                    </div>
                </div>

                <div class="chart-container">
                    <div class="chart-title">详细性能数据</div>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>时间戳</th>
                                    <th>物理内存 (KB)</th>
                                    <th>虚拟内存 (KB)</th>
                                    <th>CPU (%)</th>
                                    <th>电量 (%)</th>
                                    <th>温度 (°C)</th>
                                    <th>FPS</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for data in performance_data %}
                                {% set row_exceeded = 'exceeded-row' if 'exceeded_thresholds' in data and data.exceeded_thresholds else '' %}
                                <tr class="{{ row_exceeded }}">
                                    <td>{{ data.timestamp }}</td>
                                    <td class="{% if 'exceeded_thresholds' in data and 'rss_peak' in data.exceeded_thresholds %}exceeded-threshold{% endif %}">
                                        {{ data.memory.rss if data.memory and data.memory.rss is not none else '-' }}
                                    </td>
                                    <td class="{% if 'exceeded_thresholds' in data and 'virt_peak' in data.exceeded_thresholds %}exceeded-threshold{% endif %}">
                                        {{ data.memory.virt if data.memory and data.memory.virt is not none else '-' }}
                                    </td>
                                    <td class="{% if 'exceeded_thresholds' in data and 'cpu_peak' in data.exceeded_thresholds %}exceeded-threshold{% endif %}">
                                        {{ data.cpu if data.cpu is not none else '-' }}
                                    </td>
                                    <td>{{ data.battery if data.battery is not none else '-' }}</td>
                                    <td class="{% if 'exceeded_thresholds' in data and 'temp_peak' in data.exceeded_thresholds %}exceeded-threshold{% endif %}">
                                        {{ data.temperature if data.temperature is not none else '-' }}
                                    </td>
                                    <td class="{% if 'exceeded_thresholds' in data and 'fps_min' in data.exceeded_thresholds %}exceeded-threshold{% endif %}">
                                        {{ data.fps if data.fps is not none else '-' }}
                                    </td>
                                </tr>
                                {% else %}
                                <tr>
                                    <td colspan="7" class="no-data">没有收集到性能数据</td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="footer">
                    性能报告生成时间: {{ report_time }} | 由自动化测试系统生成
                </div>
            </div>

            <script>
                // 图表颜色配置 - 明亮现代风格
                const chartColors = {
                    rss: {
                        border: 'rgb(65, 105, 225)',      // 皇家蓝
                        background: 'rgba(65, 105, 225, 0.1)'
                    },
                    virt: {
                        border: 'rgb(148, 0, 211)',       // 紫色
                        background: 'rgba(148, 0, 211, 0.1)'
                    },
                    cpu: {
                        border: 'rgb(220, 20, 60)',       // 深红色
                        background: 'rgba(220, 20, 60, 0.1)'
                    },
                    temperature: {
                        border: 'rgb(255, 140, 0)',       // 深橙色
                        background: 'rgba(255, 140, 0, 0.1)'
                    },
                    fps: {
                        border: 'rgb(46, 139, 87)',       // 海洋绿
                        background: 'rgba(46, 139, 87, 0.1)'
                    }
                };

                // 图表配置 - 明亮风格
                const chartOptions = {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            labels: {
                                color: '#333',
                                font: {
                                    size: 14
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(255, 255, 255, 0.9)',
                            titleColor: '#333',
                            bodyColor: '#333',
                            borderColor: '#ddd',
                            borderWidth: 1,
                            padding: 12,
                            cornerRadius: 8
                        }
                    },
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit: 'minute',
                                tooltipFormat: 'YYYY-MM-DD HH:mm:ss',
                                displayFormats: {
                                    minute: 'HH:mm'
                                }
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#666',
                                font: {
                                    size: 12
                                }
                            }
                        }
                    }
                };

                // 创建图表函数
                function createChart(canvasId, data, label, colorConfig) {
                    console.log(`创建图表: ${canvasId}`);
                    const ctx = document.getElementById(canvasId);
                    if (!ctx) {
                        console.error(`Canvas元素未找到: ${canvasId}`);
                        return;
                    }

                    // 检查是否有有效数据
                    const hasValidData = data.some(value => value !== null && !isNaN(value));

                    if (!hasValidData) {
                        console.log(`${label}没有有效数据`);
                        ctx.parentElement.innerHTML += `
                            <div class="no-data">
                                <p>没有可用的${label}数据</p>
                            </div>
                        `;
                        return;
                    }

                    console.log(`${label}有有效数据，创建图表...`);

                    // 创建图表
                    try {
                        new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: JSON.parse('{{ chart_data_json }}').timestamps,
                                datasets: [{
                                    label: label,
                                    data: data,
                                    borderColor: colorConfig.border,
                                    backgroundColor: colorConfig.background,
                                    borderWidth: 3,
                                    pointRadius: 4,
                                    pointBackgroundColor: colorConfig.border,
                                    tension: 0.2,
                                    fill: true
                                }]
                            },
                            options: chartOptions
                        });
                        console.log(`${label}图表创建成功`);
                    } catch (error) {
                        console.error(`创建${label}图表失败:`, error);
                    }
                }

                // 页面加载后初始化图表
                window.addEventListener('load', function() {
                    console.log("开始初始化图表...");

                    try {
                        const chartData = JSON.parse('{{ chart_data_json }}');
                        console.log("解析的图表数据:", chartData);

                        // 物理内存图表
                        createChart(
                            'rssChart', 
                            chartData.rss_data, 
                            '物理内存 (KB)', 
                            chartColors.rss
                        );

                        // 虚拟内存图表
                        createChart(
                            'virtChart', 
                            chartData.virt_data, 
                            '虚拟内存 (KB)', 
                            chartColors.virt
                        );

                        // CPU图表
                        createChart(
                            'cpuChart', 
                            chartData.cpu_data, 
                            'CPU使用率 (%)', 
                            chartColors.cpu
                        );

                        // 温度图表
                        createChart(
                            'tempChart', 
                            chartData.temperature_data, 
                            '温度 (°C)', 
                            chartColors.temperature
                        );

                        // FPS图表
                        createChart(
                            'fpsChart', 
                            chartData.fps_data, 
                            'FPS', 
                            chartColors.fps
                        );

                        console.log("图表初始化完成");
                    } catch (error) {
                        console.error("解析图表数据失败:", error);
                    }
                });
            </script>
        </body>
        </html>
        '''

        template = Template(template_str)

        # 渲染模板
        html_content = template.render(
            case_name=case_name,
            report_time=report_time,
            performance_data=performance_data,
            avg_rss=avg_rss,
            avg_virt=avg_virt,
            avg_cpu=avg_cpu,
            avg_fps=avg_fps,
            avg_temperature=avg_temperature,
            battery_consumption=battery_consumption,
            device_info=device_info,
            chart_data_json=chart_data_json,
            chart_js_url=cdn_source["chart_js"],
            moment_js_url=cdn_source["moment_js"],
            adapter_js_url=cdn_source["adapter_js"],
            exceeded_summary=exceeded_summary
        )

        # 保存报告
        with open(perf_report_file, "w", encoding="utf-8") as f:
            f.write(html_content)

        # logger.info(f"性能报告已生成: {perf_report_file}")
        return perf_report_file.as_uri()
    except Exception as e:
        logger.error(f"生成性能报告失败: {str(e)}")
        import traceback
        logger.debug(traceback.format_exc())
        return "性能报告生成失败"


def generate_report(case_path, success, performance_data, is_retry=False):
    """生成测试报告并返回报告URL"""
    # 确保报告目录存在
    report_dir = case_path / "report"
    report_dir.mkdir(parents=True, exist_ok=True)

    case_name = case_path.name
    log_dir = case_path / "log"

    # 在文件名中添加重试标识
    retry_suffix = "_retry" if is_retry else ""
    timestamp = time.strftime("%Y%m%d%H%M%S")
    report_file = report_dir / f"report_{case_name}{retry_suffix}_{timestamp}.html"

    try:
        if not (log_dir / "log.txt").exists():
            with open(report_file, "w", encoding="utf-8") as f:
                f.write("""
                <html><body><h1>测试异常</h1><p>日志文件缺失</p></body></html>
                """)
            return report_file.as_uri()

        # 使用Airtest生成基础报告
        subprocess.run([
            "airtest", "report", str(case_path),
            "--log", str(log_dir),
            "--outfile", str(report_file),
            "--lang", "zh"
        ], check=True, timeout=300, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


        return report_file.as_uri()
    except Exception as e:
        with open(report_file, "w", encoding="utf-8") as f:
            f.write(f"""
            <html><body><h1>报告生成失败</h1><p>原因: {str(e)}</p></body></html>
            """)
        return report_file.as_uri()


def generate_summary(execution_results, total_duration=None):
    """生成汇总报告，包含总执行时长卡片"""
    try:
        # 确保目录存在
        summary_dir = config.SUMMARY_REPORT_DIR
        summary_dir.mkdir(parents=True, exist_ok=True)

        # 统计通过和失败的用例数量
        passed = 0
        failed = 0
        for case_name, results in execution_results.items():
            # 取最后一次执行结果作为最终状态
            final_status = results[-1]["status"]
            if final_status == "通过":
                passed += 1
            else:
                failed += 1

        # 计算所有用例的平均值
        all_rss = []  # 所有用例的物理内存平均值
        all_virt = []  # 所有用例的虚拟内存平均值
        all_cpu = []  # 所有用例的CPU平均值
        all_fps = []  # 所有用例的FPS平均值
        all_temperature = []  # 所有用例的温度平均值
        all_battery_consumption = []  # 所有用例的耗电量的总值

        # 添加详细的性能数据日志
        logger.debug(f"开始生成汇总报告，共有 {len(execution_results)} 个用例")

        # 用于存储每个用例的计算结果
        case_stats = []

        for case_name, results in execution_results.items():
            # 取最后一次执行结果作为主显示结果
            last_result = results[-1]
            performance_data = last_result.get("performance_data", [])
            perf_data_points = last_result.get("perf_data_points", 0)

            # 获取执行时间
            duration = last_result.get("duration", 0)
            if isinstance(duration, (int, float)):
                duration = round(duration, 1)  # 四舍五入到1位小数
            else:
                duration = "-"

            # 获取最终状态
            final_status = last_result["status"]

            # 判断是否有重试
            has_retry = len(results) > 1
            retry_results = []
            if has_retry:
                for i, result in enumerate(results):
                    if i < len(results) - 1:  # 排除最后一次结果
                        retry_results.append({
                            "status": result["status"],
                            "log_url": result["log_url"],
                            "report_url": result["report_url"],
                            "logcat_url": result["logcat_url"],
                            "perf_url": result["perf_url"],
                            "timestamp": result["timestamp"]
                        })

            # 收集所有执行结果的链接
            all_report_urls = [result["report_url"] for result in results]
            all_perf_urls = [result["perf_url"] for result in results]
            all_log_urls = [result["log_url"] for result in results]
            all_logcat_urls = [result["logcat_url"] for result in results]

            # 如果未启用性能监控，所有性能数据标记为"N/A"
            if not config.ENABLE_PERF_MONITOR:
                case_stats.append({
                    "name": case_name,
                    "status": final_status,
                    "has_retry": has_retry,
                    "retry_results": retry_results,
                    "avg_rss": "-",
                    "avg_virt": "-",
                    "avg_cpu": "-",
                    "avg_fps": "-",
                    "avg_temp": "-",
                    "battery_consumption": "-",
                    "perf_data_points": "-",
                    "log_url": last_result["log_url"],
                    "report_url": last_result["report_url"],
                    "logcat_url": last_result["logcat_url"],
                    "perf_url": last_result["perf_url"],
                    "rss_exceeded": False,
                    "virt_exceeded": False,
                    "cpu_exceeded": False,
                    "fps_exceeded": False,
                    "temp_exceeded": False,
                    "exceeded_count": 0,
                    "duration": duration,  # 添加执行时间
                    "timestamp": last_result["timestamp"],  # 添加时间戳
                    "all_report_urls": all_report_urls,
                    "all_perf_urls": all_perf_urls,
                    "all_log_urls": all_log_urls,
                    "all_logcat_urls": all_logcat_urls,
                })
                continue

            if not performance_data:
                logger.warning(f"用例 {case_name} 的性能数据为空")
                # 检查指标是否超标
                rss_exceeded = False
                virt_exceeded = False
                cpu_exceeded = False
                fps_exceeded = False
                temp_exceeded = False
                exceeded_count = 0

                case_stats.append({
                    "name": case_name,
                    "status": final_status,
                    "has_retry": has_retry,
                    "retry_results": retry_results,
                    "avg_rss": "-",
                    "avg_virt": "-",
                    "avg_cpu": "-",
                    "avg_fps": "-",
                    "avg_temp": "-",
                    "battery_consumption": "-",
                    "perf_data_points": perf_data_points,
                    "log_url": last_result["log_url"],
                    "report_url": last_result["report_url"],
                    "logcat_url": last_result["logcat_url"],
                    "perf_url": last_result["perf_url"],
                    "rss_exceeded": rss_exceeded,
                    "virt_exceeded": virt_exceeded,
                    "cpu_exceeded": cpu_exceeded,
                    "fps_exceeded": fps_exceeded,
                    "temp_exceeded": temp_exceeded,
                    "exceeded_count": exceeded_count,
                    "duration": duration,  # 添加执行时间
                    "timestamp": last_result["timestamp"],  # 添加时间戳
                    "all_report_urls": all_report_urls,
                    "all_perf_urls": all_perf_urls,
                    "all_log_urls": all_log_urls,
                    "all_logcat_urls": all_logcat_urls,
                })
                continue

            # 提取物理内存(RSS)数据
            rss_data = [
                d['memory']['rss']
                for d in performance_data
                if d.get('memory') and isinstance(d['memory'], dict) and d['memory'].get('rss') is not None
            ]

            # 提取虚拟内存(VIRT)数据
            virt_data = [
                d['memory']['virt']
                for d in performance_data
                if d.get('memory') and isinstance(d['memory'], dict) and d['memory'].get('virt') is not None
            ]

            # 提取CPU数据
            cpu_data = [d.get('cpu') for d in performance_data if d.get('cpu') is not None]

            # 提取FPS数据
            fps_data = [d.get('fps') for d in performance_data if d.get('fps') is not None]

            # 提取温度数据
            temp_data = [d.get('temperature') for d in performance_data if d.get('temperature') is not None]

            # 计算耗电量
            battery_data = [d.get('battery') for d in performance_data if d.get('battery') is not None]
            battery_consumption = "-"
            if battery_data and len(battery_data) >= 2:
                start_battery = battery_data[0]
                end_battery = battery_data[-1]
                if start_battery is not None and end_battery is not None:
                    battery_consumption = round(start_battery - end_battery, 1)
                    all_battery_consumption.append(battery_consumption)

            # 计算物理内存平均值
            avg_rss = round(sum(rss_data) / len(rss_data)) if rss_data else "-"

            # 计算虚拟内存平均值
            avg_virt = round(sum(virt_data) / len(virt_data)) if virt_data else "-"

            # 计算CPU平均值
            avg_cpu = round(sum(cpu_data) / len(cpu_data), 1) if cpu_data else "-"

            # 计算FPS平均值
            avg_fps = round(sum(fps_data) / len(fps_data), 1) if fps_data else "-"

            # 计算温度平均值
            avg_temp = round(sum(temp_data) / len(temp_data), 1) if temp_data else "-"

            # 检查指标是否超标
            rss_exceeded = False
            virt_exceeded = False
            cpu_exceeded = False
            fps_exceeded = False
            temp_exceeded = False
            exceeded_count = 0

            # 物理内存检查
            if isinstance(avg_rss, (int, float)) and avg_rss > config.PERFORMANCE_THRESHOLDS["rss_memory"]["avg"]:
                rss_exceeded = True
                exceeded_count += 1

            # 虚拟内存检查
            if isinstance(avg_virt, (int, float)) and avg_virt > config.PERFORMANCE_THRESHOLDS["virt_memory"]["avg"]:
                virt_exceeded = True
                exceeded_count += 1

            # CPU检查
            if isinstance(avg_cpu, (int, float)) and avg_cpu > config.PERFORMANCE_THRESHOLDS["cpu"]["avg"]:
                cpu_exceeded = True
                exceeded_count += 1

            # FPS检查
            if isinstance(avg_fps, (int, float)) and avg_fps < config.PERFORMANCE_THRESHOLDS["fps"]["avg"]:
                fps_exceeded = True
                exceeded_count += 1

            # 温度检查
            if isinstance(avg_temp, (int, float)) and avg_temp > config.PERFORMANCE_THRESHOLDS["temperature"]["peak"]:
                temp_exceeded = True
                exceeded_count += 1

            # 收集整体平均值数据
            if isinstance(avg_rss, (int, float)):
                all_rss.append(avg_rss)
            if isinstance(avg_virt, (int, float)):
                all_virt.append(avg_virt)
            if isinstance(avg_cpu, (int, float)):
                all_cpu.append(avg_cpu)
            if isinstance(avg_fps, (int, float)):
                all_fps.append(avg_fps)
            if isinstance(avg_temp, (int, float)):
                all_temperature.append(avg_temp)
            if isinstance(battery_consumption, (int, float)):
                all_battery_consumption.append(battery_consumption)

            # 存储用例统计信息
            case_stats.append({
                "name": case_name,
                "status": final_status,
                "has_retry": has_retry,
                "retry_results": retry_results,
                "avg_rss": avg_rss,
                "avg_virt": avg_virt,
                "avg_cpu": avg_cpu,
                "avg_fps": avg_fps,
                "avg_temp": avg_temp,
                "battery_consumption": battery_consumption,
                "perf_data_points": perf_data_points,
                "log_url": last_result["log_url"],
                "report_url": last_result["report_url"],
                "logcat_url": last_result["logcat_url"],
                "perf_url": last_result["perf_url"],
                "rss_exceeded": rss_exceeded,
                "virt_exceeded": virt_exceeded,
                "cpu_exceeded": cpu_exceeded,
                "fps_exceeded": fps_exceeded,
                "temp_exceeded": temp_exceeded,
                "exceeded_count": exceeded_count,
                "duration": duration,  # 添加执行时间
                "timestamp": last_result["timestamp"],  # 添加时间戳
                "all_report_urls": all_report_urls,
                "all_perf_urls": all_perf_urls,
                "all_log_urls": all_log_urls,
                "all_logcat_urls": all_logcat_urls,
            })

            # 记录调试信息
            logger.debug(f"用例 {case_name} 统计: "
                         f"物理内存={avg_rss}KB, 虚拟内存={avg_virt}KB, CPU={avg_cpu}%, "
                         f"FPS={avg_fps}, 温度={avg_temp}°C, "
                         f"耗电={battery_consumption}%, 数据点={perf_data_points}， ")

        # 计算整体平均值
        def safe_avg(data):
            valid_data = [x for x in data if isinstance(x, (int, float))]
            if not valid_data:
                return 0
            return round(sum(valid_data) / len(valid_data), 1) if isinstance(valid_data[0], float) else round(
                sum(valid_data) / len(valid_data))

        overall_avg_rss = safe_avg(all_rss)
        overall_avg_virt = safe_avg(all_virt)
        overall_avg_cpu = safe_avg(all_cpu)
        overall_avg_fps = safe_avg(all_fps)
        overall_avg_temperature = safe_avg(all_temperature)

        # 修改耗电量计算方式：从平均值改为总数相加
        overall_total_battery_consumption = round(sum(all_battery_consumption), 1) if all_battery_consumption else 0

        # 记录整体平均值
        logger.debug(f"整体平均物理内存: {overall_avg_rss} KB")
        logger.debug(f"整体平均虚拟内存: {overall_avg_virt} KB")
        logger.debug(f"整体平均CPU: {overall_avg_cpu}%")
        logger.debug(f"整体平均FPS: {overall_avg_fps}")
        logger.debug(f"整体平均温度: {overall_avg_temperature}°C")
        logger.debug(f"整体总耗电量: {overall_total_battery_consumption}%")

        # 格式化总执行时长
        if total_duration is None:
            # 计算实际总时长作为后备值
            total_duration = 0
            for results in execution_results.values():
                for result in results:
                    if "duration" in result:  # 检查是否存在duration字段
                        total_duration += result["duration"]

            if total_duration == 0:
                duration_str = "未记录"
            else:
                minutes, seconds = divmod(total_duration, 60)
                hours, minutes = divmod(minutes, 60)
                duration_str = f"{int(hours)}时{int(minutes)}分{int(seconds)}秒" if hours > 0 else f"{int(minutes)}分{int(seconds)}秒"
        else:
            minutes, seconds = divmod(total_duration, 60)
            hours, minutes = divmod(minutes, 60)
            duration_str = f"{int(hours)}时{int(minutes)}分{int(seconds)}秒" if hours > 0 else f"{int(minutes)}分{int(seconds)}秒"

        # 计算超标用例数量
        exceeded_count = sum(1 for case in case_stats if case["exceeded_count"] > 0)

        # 生成 HTML 报告
        timestamp = time.strftime("%Y%m%d%H%M%S")
        summary_file = summary_dir / f"summary_report_{timestamp}.html"
        report_time = time.strftime("%Y-%m-%d %H:%M:%S")

        # 生成 HTML 报告 - 包含所有修复
        template_str = '''
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>测试汇总报告</title>
            <style>
                :root {
                    --primary-color: #3498db;
                    --success-color: #2ecc71;
                    --warning-color: #f39c12;
                    --danger-color: #e74c3c;
                    --light-bg: #f8f9fa;
                    --card-bg: #ffffff;
                    --text-color: #333333;
                    --border-color: #e0e0e0;
                    --grid-color: #f0f0f0;
                }

                body {
                    font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
                    margin: 0;
                    padding: 20px;
                    background-color: var(--light-bg);
                    color: var(--text-color);
                    line-height: 1.6;
                }

                .container {
                    max-width: 2000px;
                    margin: 0 auto;
                    display: flex;
                    flex-direction: column;
                    min-height: 100vh;
                }

                .header {
                    background: linear-gradient(135deg, var(--primary-color), #2c3e50);
                    color: white;
                    padding: 25px;
                    border-radius: 12px;
                    margin-bottom: 25px;
                    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
                    text-align: center;
                    position: relative;
                    z-index: 10;
                }

                .overview-stats {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
                    gap: 20px;
                    margin-bottom: 30px;
                }

                .overview-card {
                    background: var(--card-bg);
                    border-radius: 10px;
                    padding: 20px;
                    box-shadow: 0 4px 8px rgba(0,0,0,0.05);
                    text-align: center;
                    transition: transform 0.3s ease;
                }

                .overview-card:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 8px 16px rgba(0,0,0,0.1);
                }

                .overview-value {
                    font-size: 28px;
                    font-weight: bold;
                    margin: 10px 0;
                    color: var(--primary-color);
                }

                .overview-label {
                    font-size: 16px;
                    color: #7f8c8d;
                }

                .filter-container {
                    display: flex;
                    justify-content: flex-end;
                    margin-bottom: 20px;
                    padding: 10px;
                    background: var(--card-bg);
                    border-radius: 8px;
                    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
                    position: sticky;
                    top: 0;
                    z-index: 100;
                }

                .filter-btn {
                    padding: 8px 16px;
                    margin-left: 10px;
                    border: none;
                    border-radius: 4px;
                    background-color: var(--light-bg);
                    color: var(--text-color);
                    cursor: pointer;
                    font-weight: 500;
                    transition: all 0.3s ease;
                }

                .filter-btn:hover {
                    background-color: var(--primary-color);
                    color: white;
                }

                .filter-btn.active {
                    background-color: var(--primary-color);
                    color: white;
                    font-weight: bold;
                }

                /* 表格容器包装 */
                .table-container-wrapper {
                    display: flex;
                    flex-direction: column;
                    height: 60vh;
                    overflow: hidden;
                    background: var(--card-bg);
                    border-radius: 10px;
                    box-shadow: 0 4px 8px rgba(0,0,0,0.05);
                }

                /* 表头容器 */
                .table-header-container {
                    position: sticky;
                    top: 0;
                    z-index: 300;
                    background: var(--light-bg);
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                }

                /* 内容容器 */
                .table-body-container {
                    flex: 1;
                    overflow-y: auto;
                    position: relative;
                }

                .fixed-header {
                    width: 100%;
                    border-collapse: separate;
                    border-spacing: 0;
                }

                #resultsTable {
                    border-collapse: separate;
                    border-spacing: 0;
                    width: 100%;
                }

                th {
                    padding: 15px 15px !important;
                    min-height: 60px;
                    vertical-align: middle;
                    text-align: left;
                }

                td {
                    padding: 15px 15px !important;
                    min-height: 60px;
                    vertical-align: middle;
                }

                /* 用例名称列固定宽度 */
                .case-name-column {
                    min-width: 250px;
                    max-width: 300px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                /* 状态列固定宽度 */
                .status-column {
                    min-width: 120px;
                    max-width: 150px;
                }

                /* 性能数据列固定宽度 */
                .perf-column {
                    min-width: 100px;
                    max-width: 120px;
                }

                /* 执行时间列 */
                .duration-column {
                    min-width: 100px;
                    max-width: 120px;
                }

                /* 链接列固定宽度 */
                .link-column {
                    min-width: 80px;
                    max-width: 100px;
                }

                /* 排序指示器样式 */
                th.sortable {
                    cursor: pointer;
                    position: relative;
                    padding-right: 25px;
                }

                th.sortable::after {
                    content: "↕";
                    position: absolute;
                    right: 8px;
                    top: 50%;
                    transform: translateY(-50%);
                    opacity: 0.5;
                    font-size: 14px;
                    transition: opacity 0.3s;
                }

                th.sortable:hover::after {
                    opacity: 1;
                }

                th.sortable.asc::after {
                    content: "↑";
                    opacity: 1;
                }

                th.sortable.desc::after {
                    content: "↓";
                    opacity: 1;
                }

                /* 重试结果样式 - 完全重写 */
                .retry-badge {
                    display: inline-block;
                    padding: 3px 8px;
                    border-radius: 4px;
                    font-size: 12px;
                    margin-left: 6px;
                    vertical-align: middle;
                    white-space: nowrap;
                }

                .retry-success {
                    background-color: #d4edda;
                    color: #155724;
                }

                .retry-failure {
                    background-color: #f8d7da;
                    color: #721c24;
                }

                .retry-history {
                    position: relative;
                    display: inline-block;
                    cursor: pointer;
                    margin-left: 6px;
                }

                .retry-history::after {
                    content: "ⓘ";
                    font-size: 14px;
                    color: #3498db;
                    transition: all 0.2s ease;
                }

                .retry-history:hover::after {
                    color: #2c3e50;
                    transform: scale(1.2);
                }

                .retry-details {
                    display: none;
                    position: fixed;
                    z-index: 10000;
                    min-width: 350px;
                    max-width: 500px;
                    max-height: 300px;
                    overflow-y: auto;
                    background: white;
                    border: 1px solid #e0e0e0;
                    border-radius: 10px;
                    padding: 20px;
                    box-shadow: 0 6px 20px rgba(0,0,0,0.15);
                    font-size: 14px;
                    line-height: 1.5;
                    animation: fadeIn 0.3s ease;
                }

                @keyframes fadeIn {
                    from { opacity: 0; transform: translateY(10px); }
                    to { opacity: 1; transform: translateY(0); }
                }

                .retry-details h4 {
                    margin-top: 0;
                    margin-bottom: 15px;
                    color: #2c3e50;
                    border-bottom: 2px solid #f0f0f0;
                    padding-bottom: 10px;
                    font-size: 16px;
                }

                .retry-item {
                    margin-bottom: 15px;
                    padding-bottom: 15px;
                    border-bottom: 1px solid #f5f5f5;
                }

                .retry-item:last-child {
                    border-bottom: none;
                    margin-bottom: 0;
                    padding-bottom: 0;
                }

                .retry-status {
                    font-weight: bold;
                    margin-bottom: 8px;
                    display: flex;
                    align-items: center;
                }

                .retry-badge {
                    margin-left: 8px;
                    font-size: 11px;
                    padding: 2px 6px;
                }

                .retry-links {
                    display: grid;
                    grid-template-columns: repeat(2, 1fr);
                    gap: 8px;
                    margin-top: 10px;
                }

                .retry-links a {
                    display: block;
                    padding: 6px 10px;
                    background-color: #f8f9fa;
                    border-radius: 4px;
                    color: #3498db;
                    text-decoration: none;
                    text-align: center;
                    transition: all 0.2s ease;
                    border: 1px solid #e0e0e0;
                }

                .retry-links a:hover {
                    background-color: #3498db;
                    color: white;
                    border-color: #3498db;
                }

                .retry-timestamp {
                    font-size: 12px;
                    color: #7f8c8d;
                    margin-top: 5px;
                    display: flex;
                    align-items: center;
                }

                .retry-timestamp::before {
                    content: "🕒";
                    margin-right: 5px;
                }

                .status-passed {
                    color: var(--success-color);
                    font-weight: bold;
                }

                .status-failed {
                    color: var(--danger-color);
                    font-weight: bold;
                }

                .avg-value {
                    font-weight: bold;
                    color: #3498db;
                }

                /* 超标标记样式 */
                .summary-exceeded {
                    background-color: #ffcccc !important;
                    position: relative;
                }
                .summary-exceeded::after {
                    content: "⚠";
                    position: absolute;
                    right: 5px;
                    color: #d9534f;
                }
                .summary-warning-row {
                    background-color: #fff3f3 !important;
                }

                .footer {
                    text-align: center;
                    margin-top: 30px;
                    color: #7f8c8d;
                    font-size: 14px;
                    position: relative;
                    z-index: 10;
                }

                /* 响应式设计 */
                @media (max-width: 768px) {
                    .overview-stats {
                        grid-template-columns: 1fr;
                    }

                    .filter-container {
                        justify-content: center;
                    }

                    table {
                        font-size: 14px;
                    }

                    th, td {
                        padding: 8px 10px;
                    }

                    th:first-child, td:first-child {
                        width: 150px;
                        min-width: 150px;
                        max-width: 200px;
                    }

                    th, td {
                        width: auto !important;
                    }

                    .retry-details {
                        min-width: 280px;
                        max-width: 90vw;
                        left: 5vw !important;
                        right: auto !important;
                    }

                    .retry-links {
                        grid-template-columns: 1fr;
                    }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>测试汇总报告</h1>
                    <p>生成时间: {{ report_time }}</p>
                </div>

                <!-- 顶部统计卡片 - 包含总时长卡片 -->
                <div class="overview-stats">
                    <div class="overview-card">
                        <div class="overview-value">{{ duration_str }}</div>
                        <div class="overview-label">总执行时长</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ total }}</div>
                        <div class="overview-label">总用例数</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ passed }}</div>
                        <div class="overview-label">通过用例</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ failed }}</div>
                        <div class="overview-label">失败用例</div>
                    </div>
                    {% if enable_perf_monitor %}
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_avg_rss }} KB</div>
                        <div class="overview-label">平均物理内存</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_avg_virt }} KB</div>
                        <div class="overview-label">平均虚拟内存</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_avg_cpu }} %</div>
                        <div class="overview-label">平均CPU</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_avg_fps }}</div>
                        <div class="overview-label">平均FPS</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_avg_temperature }} °C</div>
                        <div class="overview-label">平均温度</div>
                    </div>
                    <div class="overview-card">
                        <div class="overview-value">{{ overall_total_battery_consumption }} %</div>
                        <div class="overview-label">总耗电量</div>
                    </div>
                    {% endif %}
                </div>

                <!-- 结果筛选器 -->
                <div class="filter-container">
                    <span>筛选结果:</span>
                    <button class="filter-btn active" data-filter="all">全部 ({{ total }})</button>
                    <button class="filter-btn" data-filter="passed">通过 ({{ passed }})</button>
                    <button class="filter-btn" data-filter="failed">失败 ({{ failed }})</button>
                    {% if enable_perf_monitor %}
                    <button class="filter-btn" data-filter="exceeded">超标 ({{ exceeded_count }})</button>
                    {% endif %}
                </div>

                <!-- 表格容器包装 - 分离表头和内容 -->
                <div class="table-container-wrapper">
                    <!-- 固定表头 -->
                    <div class="table-header-container">
                        <table class="fixed-header">
                            <thead>
                                <tr>
                                    <th class="sortable case-name-column" data-sort="name">用例名称</th>
                                    <th class="sortable status-column" data-sort="status">执行结果</th>
                                    {% if enable_perf_monitor %}
                                    <th class="sortable perf-column" data-sort="rss">物理内存 (KB)</th>
                                    <th class="sortable perf-column" data-sort="virt">虚拟内存 (KB)</th>
                                    <th class="sortable perf-column" data-sort="cpu">CPU (%)</th>
                                    <th class="sortable perf-column" data-sort="fps">FPS</th>
                                    <th class="sortable perf-column" data-sort="temp">温度 (°C)</th>
                                    <th class="sortable perf-column" data-sort="points">性能数据点</th>
                                    {% endif %}
                                    <!-- 新增执行时间列 -->
                                    <th class="sortable duration-column" data-sort="duration">执行时间 (秒)</th>
                                    <th class="link-column">执行日志</th>
                                    <th class="link-column">测试报告</th>
                                    {% if enable_logcat %}
                                    <th class="link-column">Logcat</th>
                                    {% endif %}
                                    {% if enable_perf_monitor %}
                                    <th class="link-column">性能报告</th>
                                    {% endif %}
                                </tr>
                            </thead>
                        </table>
                    </div>

                    <!-- 可滚动内容 -->
                    <div class="table-body-container" id="scrollableBody">
                        <table id="resultsTable">
                            <tbody>
                                {% for case in case_stats %}
                                <tr class="result-row {% if case.exceeded_count > 0 %}summary-warning-row{% endif %}" 
                                    data-status="{{ 'passed' if case.status == '通过' else 'failed' }}"
                                    data-exceeded="{{ 'true' if case.exceeded_count > 0 else 'false' }}"
                                    data-name="{{ case.name }}"
                                    data-status-value="{{ case.status }}"
                                    data-rss="{{ case.avg_rss if case.avg_rss != '-' else 0 }}"
                                    data-virt="{{ case.avg_virt if case.avg_virt != '-' else 0 }}"
                                    data-cpu="{{ case.avg_cpu if case.avg_cpu != '-' else 0 }}"
                                    data-fps="{{ case.avg_fps if case.avg_fps != '-' else 0 }}"
                                    data-temp="{{ case.avg_temp if case.avg_temp != '-' else 0 }}"
                                    data-points="{{ case.perf_data_points }}"
                                    data-duration="{{ case.duration if case.duration != '-' else 0 }}">
                                    <td class="case-name-column" title="{{ case.name }}">
                                        <div style="display: flex; align-items: center;">
                                            <span style="flex: 1; overflow: hidden; text-overflow: ellipsis;">
                                                {{ case.name }}
                                            </span>
                                            {% if case.has_retry %}
                                            <span class="retry-history">
                                                <div class="retry-details">
                                                    <h4>执行历史 (共 {{ case.retry_results|length + 1 }} 次)</h4>

                                                    <!-- 显示所有重试结果 -->
                                                    {% for i in range(case.retry_results|length) %}
                                                    <div class="retry-item">
                                                        <div class="retry-status">
                                                            {{ i+1 }}. {{ case.retry_results[i].status }}
                                                            <span class="retry-badge {% if case.retry_results[i].status == '通过' %}retry-success{% else %}retry-failure{% endif %}">
                                                                第{{ i+1 }}次执行
                                                            </span>
                                                        </div>
                                                        <div class="retry-timestamp">{{ case.retry_results[i].timestamp }}</div>
                                                        <div class="retry-links">
                                                            <a href="{{ case.all_log_urls[i] }}" target="_blank">执行日志</a>
                                                            <a href="{{ case.all_report_urls[i] }}" target="_blank">测试报告</a>
                                                            {% if enable_logcat %}
                                                            <a href="{{ case.all_logcat_urls[i] }}" target="_blank">Logcat</a>
                                                            {% endif %}
                                                            {% if enable_perf_monitor %}
                                                            <a href="{{ case.all_perf_urls[i] }}" target="_blank">性能报告</a>
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                    {% endfor %}

                                                    <!-- 显示最后一次执行结果 -->
                                                    <div class="retry-item">
                                                        <div class="retry-status">
                                                            {{ case.retry_results|length + 1 }}. {{ case.status }}
                                                            <span class="retry-badge {% if case.status == '通过' %}retry-success{% else %}retry-failure{% endif %}">
                                                                最后一次执行
                                                            </span>
                                                        </div>
                                                        <div class="retry-timestamp">{{ case.timestamp }}</div>
                                                        <div class="retry-links">
                                                            <a href="{{ case.log_url }}" target="_blank">执行日志</a>
                                                            <a href="{{ case.report_url }}" target="_blank">测试报告</a>
                                                            {% if enable_logcat %}
                                                            <a href="{{ case.logcat_url }}" target="_blank">Logcat</a>
                                                            {% endif %}
                                                            {% if enable_perf_monitor %}
                                                            <a href="{{ case.perf_url }}" target="_blank">性能报告</a>
                                                            {% endif %}
                                                        </div>
                                                    </div>
                                                </div>
                                            </span>
                                            {% endif %}
                                        </div>
                                    </td>
                                    <td class="status-column status-{% if case.status == '通过' %}passed{% else %}failed{% endif %}">
                                        <div style="display: flex; align-items: center;">
                                            <span style="flex: 1;">{{ case.status }}</span>
                                            {% if case.has_retry and case.status == '通过' %}
                                                <span class="retry-badge retry-success">重试成功</span>
                                            {% elif case.has_retry %}
                                                <span class="retry-badge retry-failure">重试失败</span>
                                            {% endif %}
                                        </div>
                                    </td>
                                    {% if enable_perf_monitor %}
                                    <td class="perf-column avg-value {% if case.rss_exceeded %}summary-exceeded{% endif %}">
                                        {% if case.avg_rss != '-' %}
                                            {{ case.avg_rss }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="perf-column avg-value {% if case.virt_exceeded %}summary-exceeded{% endif %}">
                                        {% if case.avg_virt != '-' %}
                                            {{ case.avg_virt }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="perf-column avg-value {% if case.cpu_exceeded %}summary-exceeded{% endif %}">
                                        {% if case.avg_cpu != '-' %}
                                            {{ case.avg_cpu }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="perf-column avg-value {% if case.fps_exceeded %}summary-exceeded{% endif %}">
                                        {% if case.avg_fps != '-' %}
                                            {{ case.avg_fps }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="perf-column avg-value {% if case.temp_exceeded %}summary-exceeded{% endif %}">
                                        {% if case.avg_temp != '-' %}
                                            {{ case.avg_temp }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="perf-column avg-value">
                                        {{ case.perf_data_points }}
                                    </td>
                                    {% endif %}
                                    <!-- 新增执行时间列 -->
                                    <td class="duration-column avg-value">
                                        {% if case.duration != '-' %}
                                            {{ case.duration }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                    <td class="link-column"><a href="{{ case.log_url }}" target="_blank">查看</a></td>
                                    <td class="link-column"><a href="{{ case.report_url }}" target="_blank">查看</a></td>
                                    {% if enable_logcat %}
                                    <td class="link-column"><a href="{{ case.logcat_url }}" target="_blank">查看</a></td>
                                    {% endif %}
                                    {% if enable_perf_monitor %}
                                    <td class="link-column"><a href="{{ case.perf_url }}" target="_blank">查看</a></td>
                                    {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="footer">
                    汇总报告生成时间: {{ report_time }} | 由自动化测试系统生成
                </div>
            </div>

            <script>
                // 当前排序状态
                let currentSort = {
                    column: null,
                    direction: 'asc' // 'asc' 或 'desc'
                };

                // DOM 加载完成后初始化
                document.addEventListener('DOMContentLoaded', function() {
                    // 初始化行索引
                    const rows = document.querySelectorAll('#resultsTable tbody tr');
                    rows.forEach((row, index) => {
                        row.dataset.index = index;
                    });

                    // 初始化筛选按钮事件
                    document.querySelectorAll('.filter-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            filterResults(this.dataset.filter);
                        });
                    });

                    // 初始化排序按钮事件
                    document.querySelectorAll('th.sortable').forEach(th => {
                        th.addEventListener('click', function() {
                            sortTable(this.dataset.sort);
                        });
                    });

                    // 重试历史弹窗处理 - 完整实现
                    document.querySelectorAll('.retry-history').forEach(element => {
                        const details = element.querySelector('.retry-details');
                        let hideTimer = null;
                        let isHovering = false;

                        // 显示弹窗
                        function showDetails() {
                            clearTimeout(hideTimer);
                            if (details) {
                                // 固定位置显示弹窗
                                details.style.display = 'block';

                                // 定位在信息图标附近
                                const iconRect = element.getBoundingClientRect();
                                details.style.left = (iconRect.right + 10) + 'px';
                                details.style.top = (iconRect.top) + 'px';

                                // 防止超出视口
                                const rect = details.getBoundingClientRect();
                                const viewportWidth = window.innerWidth;
                                const viewportHeight = window.innerHeight;

                                if (rect.right > viewportWidth) {
                                    details.style.left = (iconRect.left - rect.width - 10) + 'px';
                                }
                                if (rect.bottom > viewportHeight) {
                                    details.style.top = (iconRect.bottom - rect.height) + 'px';
                                }
                            }
                        }

                        // 隐藏弹窗（带延迟）
                        function hideDetails() {
                            hideTimer = setTimeout(() => {
                                if (details && !isHovering) {
                                    details.style.display = 'none';
                                }
                            }, 300);
                        }

                        // 鼠标移入图标时显示弹窗
                        element.addEventListener('mouseenter', function() {
                            isHovering = true;
                            showDetails();
                        });

                        // 鼠标移出图标时准备隐藏
                        element.addEventListener('mouseleave', function() {
                            isHovering = false;
                            hideDetails();
                        });

                        // 处理弹窗本身的鼠标事件
                        if (details) {
                            details.addEventListener('mouseenter', function() {
                                clearTimeout(hideTimer);
                                isHovering = true;
                            });

                            details.addEventListener('mouseleave', function() {
                                isHovering = false;
                                hideDetails();
                            });
                        }
                    });

                    // 初始同步列宽
                    syncColumnWidths();
                });

                // 结果筛选功能
                function filterResults(status) {
                    // 更新按钮状态
                    document.querySelectorAll('.filter-btn').forEach(btn => {
                        btn.classList.remove('active');
                        if (btn.dataset.filter === status) {
                            btn.classList.add('active');
                        }
                    });

                    // 获取所有行
                    const rows = document.querySelectorAll('.result-row');

                    // 根据状态显示/隐藏行
                    rows.forEach(row => {
                        row.style.display = 'none';

                        if (status === 'all') {
                            row.style.display = '';
                        } 
                        else if (status === 'passed' && row.dataset.status === 'passed') {
                            row.style.display = '';
                        } 
                        else if (status === 'failed' && row.dataset.status === 'failed') {
                            row.style.display = '';
                        } 
                        else if (status === 'exceeded' && row.dataset.exceeded === 'true') {
                            row.style.display = '';
                        }
                    });
                }

                // 高性能表格排序
                function sortTable(columnKey) {
                    const table = document.getElementById('resultsTable');
                    const tbody = table.querySelector('tbody');
                    const rows = Array.from(tbody.querySelectorAll('tr'));
                    const header = document.querySelector(`.fixed-header th[data-sort="${columnKey}"]`);

                    // 清除其他列的排序状态
                    document.querySelectorAll('th.sortable').forEach(th => {
                        if (th !== header) {
                            th.classList.remove('asc', 'desc');
                        }
                    });

                    // 确定排序方向
                    let sortDirection = 'asc';
                    if (currentSort.column === columnKey) {
                        sortDirection = currentSort.direction === 'asc' ? 'desc' : 'asc';
                    }

                    // 更新当前排序状态
                    currentSort = {
                        column: columnKey,
                        direction: sortDirection
                    };

                    // 更新表头样式
                    header.classList.remove('asc', 'desc');
                    header.classList.add(sortDirection);

                    // 高性能排序算法
                    rows.sort((a, b) => {
                        const aValue = a.dataset[columnKey];
                        const bValue = b.dataset[columnKey];

                        // 数值类型列的特殊处理
                        const numericalColumns = ['rss', 'virt', 'cpu', 'fps', 'temp', 'points', 'duration'];
                        if (numericalColumns.includes(columnKey)) {
                            const aNum = parseFloat(aValue) || 0;
                            const bNum = parseFloat(bValue) || 0;

                            // 降序排列（高值在前）
                            if (sortDirection === 'desc') {
                                return bNum - aNum;
                            } 
                            // 升序排列（低值在前）
                            else {
                                return aNum - bNum;
                            }
                        } 
                        // 文本类型列
                        else {
                            if (sortDirection === 'desc') {
                                return bValue.localeCompare(aValue);
                            } else {
                                return aValue.localeCompare(bValue);
                            }
                        }
                    });

                    // 重新添加行到表格
                    tbody.innerHTML = '';
                    rows.forEach(row => tbody.appendChild(row));

                    // 重新同步列宽
                    syncColumnWidths();
                }

                // 同步表头和内容列宽
                function syncColumnWidths() {
                    const headerCells = document.querySelectorAll('.fixed-header th');
                    const bodyCells = document.querySelectorAll('#resultsTable tr:first-child td');

                    if (headerCells.length === 0 || bodyCells.length === 0) return;
                    if (headerCells.length !== bodyCells.length) return;

                    headerCells.forEach((headerCell, index) => {
                        const width = bodyCells[index].offsetWidth + 'px';
                        headerCell.style.width = width;
                        bodyCells[index].style.width = width;
                    });
                }

                // 窗口调整大小时重新同步
                window.addEventListener('resize', syncColumnWidths);
            </script>
        </body>
        </html>
        '''

        template = Template(template_str)

        html_content = template.render(
            total=len(execution_results),
            passed=passed,
            failed=failed,
            exceeded_count=exceeded_count,
            case_stats=case_stats,
            overall_avg_rss=overall_avg_rss,
            overall_avg_virt=overall_avg_virt,
            overall_avg_cpu=overall_avg_cpu,
            overall_avg_fps=overall_avg_fps,
            overall_avg_temperature=overall_avg_temperature,
            overall_total_battery_consumption=overall_total_battery_consumption,
            report_time=report_time,
            duration_str=duration_str,
            enable_perf_monitor=config.ENABLE_PERF_MONITOR,
            enable_logcat=config.ENABLE_LOGCAT
        )

        with open(summary_file, 'w', encoding='utf-8') as f:
            f.write(html_content)

        logger.info(f"汇总报告已生成: {summary_file.as_uri()}")
        return summary_file.as_uri()
    except Exception as e:
        logger.error(f"生成汇总报告失败: {str(e)}")
        import traceback
        logger.debug(traceback.format_exc())
        return None